package com.mpsc.sharding.util;


import com.alibaba.ttl.TransmittableThreadLocal;
import org.apache.commons.lang3.ObjectUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public final class CacheHolder {

    private CacheHolder() {
        throw new IllegalStateException("Utility class");
    }

    public static String CONTEXT_USER_INFO ="context_user_info";


    /**
     * 使用TTL可以使子线程池能访问到父线程的threadLocal变量
     */
    private static final ThreadLocal<Map<Object, Object>> cacheData =
            new TransmittableThreadLocal<>();

    public static void set(Object key, Object value) {
        try {
            if(cacheData.get() == null) {
                cacheData.set(new ConcurrentHashMap<>(16));
            }
            if (ObjectUtils.allNotNull(key, value)) {
                cacheData.get().put(key, value);
            }

        } catch (Exception e) {
            throw new RuntimeException("设置缓存出错");
        }
    }

    public static Object get(Object key) {
        if(cacheData.get() == null) {
            cacheData.set(new ConcurrentHashMap<>(16));
        }
        Object value = cacheData.get().get(key);

        return value;
    }

    public static void remove() {
        try {
            cacheData.remove();
        } catch (Exception e) {
            System.out.println("[CacheHolder] remove cache fail"+ e);
        }
    }

    public static void init() {
        // 主线程手动初始化cacheData变量，后续子线程可以共享改变量
        cacheData.set(new ConcurrentHashMap<>(16));
    }
}
